import 'package:floating_draggable_widget/floating_draggable_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:gluz/app/common/common_button.dart';
import 'package:gluz/app/common/tabbar_indicator.dart';
import '../../../utils/colors.dart';
import '../controllers/home_hd_controller.dart';

class HomeHdView extends GetView<HomeHdController> {
  const HomeHdView({super.key});

  @override
  Widget build(BuildContext context) {
    return _HomeHdViewState();
  }
}

class _HomeHdViewState extends StatefulWidget {
  @override
  _HomeHdViewStateState createState() => _HomeHdViewStateState();
}

class _HomeHdViewStateState extends State<_HomeHdViewState>
    with TickerProviderStateMixin {
  late TabController _tabController;
  late HomeHdController controller;

  @override
  void initState() {
    super.initState();
    controller = Get.find<HomeHdController>();
    _tabController = TabController(length: 2, vsync: this);
    _tabController.addListener(() {
      if (_tabController.indexIsChanging) {
        controller.selectedTabIndex.value = _tabController.index;
      }
    });
    controller.tabController = _tabController;
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppColors.color_F7F7F7,
      body: Container(
        child: FloatingDraggableWidget(
          floatingWidget: Image.asset('assets/images/home/home_trans_icon.png'),
          autoAlignType: AlignmentType.onlyRight,
          autoAlign: true,
          disableBounceAnimation: true,
          floatingWidgetHeight: 60,
          floatingWidgetWidth: 80,
          dx: Get.size.width - 80,
          dy: 100,
          screenHeight: Get.size.height - Get.bottomBarHeight,
          mainScreenWidget: Stack(
            children: [
              Container(color: AppColors.color_F7F7F7),
              Image.asset('assets/images/home_hd/home_hd_top_bg.png'),
              // 主内容
              _buildMainContent(),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建主内容
  Widget _buildMainContent() {
    return SingleChildScrollView(
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 10),
        child: Column(
          spacing: 10,
          children: [
            // 顶部背景图和文字
            _buildTopBanner(),
            // TabBar和地区选择
            _buildTabAndLocationSection(),
            // 功能图标网格
            _buildFunctionIconsGrid(),
            // 会员中心
            _buildMemberCenter(),
            // 介绍按钮
            _buildIntroButtons(),
            // 热门会议
            _buildHotMeetings(),
            // 最新货源
            _buildLatestFreight(),
            SizedBox(height: 20.h),
          ],
        ),
      ),
    );
  }

  /// 构建顶部背景图和文字
  Widget _buildTopBanner() {
    return Container(
      height: 180.h,
      width: double.infinity,
      child: SafeArea(
        child: Padding(
          padding: EdgeInsets.symmetric(horizontal: 20.w),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              const SizedBox(height: 15),
              Image.asset(
                'assets/images/home_hd/home_hd_title.png',
                height: 20,
              ),
              Image.asset(
                'assets/images/home_hd/home_hd_title2.png',
                height: 20,
              ),
              const SizedBox(height: 5),
              Image.asset(
                'assets/images/home_hd/home_hd_title_ru.png',
                height: 30,
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建TabBar和地区选择
  Widget _buildTabAndLocationSection() {
    return Container(
      child: Obx(() {
        return Stack(
          children: [
            Positioned.fill(
              child: Image.asset(
                'assets/images/home_hd/home_hd_tab_bg.png',
                fit: BoxFit.fill,
              ),
            ),
            if (controller.selectedTabIndex.value == 0)
              Positioned.fill(
                child: Image.asset(
                  'assets/images/home_hd/home_hd_left_tab.png',
                  fit: BoxFit.fill,
                ),
              ),
            if (controller.selectedTabIndex.value == 1)
              Positioned.fill(
                child: Image.asset(
                  'assets/images/home_hd/home_hd_right_tab.png',
                  fit: BoxFit.fill,
                ),
              ),
            Column(
              children: [
                // TabBar
                _buildTabBar(),
                SizedBox(height: 10.h),
                // 地区选择
                _buildLocationSelection(),
                SizedBox(height: 10.h),
                // 按钮
                _buildActionButtons(),

                SizedBox(height: 15.h),
              ],
            ),
          ],
        );
      }),
    );
  }

  /// 构建TabBar
  Widget _buildTabBar() {
    return Container(
      height: 50.h,
      child: Stack(
        children: [
          // TabBar组件
          TabBar(
            controller: _tabController,
            onTap: (index) => controller.onTabChanged(index),
            indicator: TabBarCustomIndicator(indWidth: 40, indHeight: 3, radius: 1.5),
            dividerColor: Colors.transparent,
            labelColor: Colors.blue,
            unselectedLabelColor: Colors.white,
            labelStyle: TextStyle(
              fontSize: 16.sp,
              fontWeight: FontWeight.bold,
            ),
            unselectedLabelStyle: TextStyle(
              fontSize: 14.sp,
              fontWeight: FontWeight.bold,
            ),
            tabs: const [
              Tab(text: '大件运输'),
              Tab(text: '小件快递'),
            ],
          ),
        ],
      ),
    );
  }

  /// 构建地区选择
  Widget _buildLocationSelection() {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16),
      child: Row(
        children: [
          // 出发地
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Obx(
                      () =>
                      InkWell(
                        onTap: controller.onTapFromCity,
                        child: Text(
                          controller.fromCity.value,
                          style: TextStyle(
                            fontSize: 16.sp,
                            fontWeight: FontWeight.w500,
                            color: AppColors.color_333333,
                          ),
                        ),
                      ),
                ),
              ],
            ),
          ),
          // 交换按钮
          GestureDetector(
            onTap: controller.swapCities,
            child: Container(
              width: 40.w,
              height: 40.w,
              decoration: BoxDecoration(
                color: AppColors.color_F5F5F5,
                shape: BoxShape.circle,
              ),
              child: Icon(
                Icons.swap_horiz,
                color: AppColors.color_666666,
                size: 20.sp,
              ),
            ),
          ),
          // 目的地
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.end,
              children: [
                Obx(
                      () =>
                      InkWell(
                        onTap: controller.onTapToCity,
                        child: Text(
                          controller.toCity.value,
                          style: TextStyle(
                            fontSize: 16.sp,
                            fontWeight: FontWeight.w500,
                            color: AppColors.color_333333,
                          ),
                        ),
                      ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  /// 构建操作按钮
  Widget _buildActionButtons() {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 16),
      child: Row(
        children: [
          GestureDetector(
            onTap: controller.onFreightSearch,
            child: Container(
              width: 95,
              height: 44.h,
              decoration: BoxDecoration(
                color: AppColors.color_F5F5F5,
                borderRadius: BorderRadius.circular(22.r),
              ),
              child: Center(
                child: Text(
                  '货源搜索',
                  style: TextStyle(
                    fontSize: 16.sp,
                    color: AppColors.color_666666,
                  ),
                ),
              ),
            ),
          ),
          SizedBox(width: 12.w),
          Expanded(
            child: SizedBox(
              height: 44,
              child: GLGradientButton(
                onPressed: controller.onShipNow,
                child: Text(
                  '立即发货',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 16,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建功能图标网格
  Widget _buildFunctionIconsGrid() {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12.r),
      ),
      child: GridView.builder(
        padding: EdgeInsets.zero,
        shrinkWrap: true,
        physics: const NeverScrollableScrollPhysics(),
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 4,
          childAspectRatio: 1.0,
          // crossAxisSpacing: 16,
          // mainAxisSpacing: 16,
        ),
        itemCount: controller.functionIcons.length,
        itemBuilder: (context, index) {
          final item = controller.functionIcons[index];
          return InkWell(
            onTap: () => controller.onFunctionIconTap(index),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Stack(
                  children: [
                    Image.asset(item['icon'], width: 40.w, height: 40.w),
                    if (item['badge'] > 0)
                      Positioned(
                        right: 0,
                        top: 0,
                        child: Container(
                          padding: EdgeInsets.symmetric(
                            horizontal: 4.w,
                            vertical: 1.h,
                          ),
                          decoration: BoxDecoration(
                            color: AppColors.color_F44336,
                            borderRadius: BorderRadius.circular(10.r),
                          ),
                          child: Text(
                            item['badge'] > 99
                                ? '99+'
                                : item['badge'].toString(),
                            style: TextStyle(
                              color: Colors.white,
                              fontSize: 7.sp,
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                        ),
                      ),
                  ],
                ),
                SizedBox(height: 8.h),
                Text(
                  item['title'],
                  style: TextStyle(
                    fontSize: 12.sp,
                    color: AppColors.color_333333,
                  ),
                  textAlign: TextAlign.center,
                ),
              ],
            ),
          );
        },
      ),
    );
  }

  /// 构建会员中心
  Widget _buildMemberCenter() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12.r),
        gradient: LinearGradient(
          begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [
          Color(0xFFFFFADD),
          Color(0xFFFFFFFF),
        ]),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Text(
                '会员中心',
                style: TextStyle(
                  fontSize: 16.sp,
                  fontWeight: FontWeight.bold,
                  color: AppColors.color_333333,
                ),
              ),
              SizedBox(width: 8.w),
              Container(
                padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 2.h),
                decoration: BoxDecoration(
                  color: AppColors.color_FF9800,
                  borderRadius: BorderRadius.circular(10.r),
                ),
                child: Text(
                  '限时优惠',
                  style: TextStyle(fontSize: 8.sp, color: Colors.white),
                ),
              ),
              const Spacer(),
              Container(
                padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 2.h),
                decoration: BoxDecoration(
                  color: AppColors.color_FFB74D,
                  borderRadius: BorderRadius.circular(10.r),
                ),
                child: Text(
                  '更多会员福利>',
                  style: TextStyle(fontSize: 8.sp, color: AppColors.color_7D0A00, fontWeight: FontWeight.bold),
                ),
              ),
            ],
          ),
          SizedBox(height: 12.h),
          GestureDetector(
            onTap: controller.onMemberCenterTap,
            child: Image.asset(controller.vipImg, fit: BoxFit.fitWidth,),
          ),
        ],
      ),
    );
  }

  /// 构建介绍按钮
  Widget _buildIntroButtons() {
    return Container(
      child: Row(
        children: [
          Expanded(
            child: Stack(
              children: [
                Image.asset(
                  controller.translateImg,
                  fit: BoxFit.cover,
                ),
                Positioned(
                  bottom: 15,
                  right: 15,
                  child: Image.asset('assets/images/home_hd/home_hd_translate_icon.png', width: 40,),
                ),
              ],
            ),
          ),
          SizedBox(width: 8.w),
          Expanded(
            child: Stack(
              children: [
                Image.asset(
                  controller.transportImg,
                  fit: BoxFit.cover,
                ),
                Positioned(
                  bottom: 15,
                  right: 15,
                  child: Image.asset('assets/images/home_hd/home_hd_transport_icon.png', width: 40,),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  /// 构建热门会议
  Widget _buildHotMeetings() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12.r),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Text(
                '热门会议',
                style: TextStyle(
                  fontSize: 16.sp,
                  fontWeight: FontWeight.w600,
                  color: AppColors.color_333333,
                ),
              ),
              SizedBox(width: 4.w),
              Icon(Icons.bar_chart, size: 16.sp, color: AppColors.color_F44336),
              const Spacer(),
              Text(
                '全部会议 >',
                style: TextStyle(
                  fontSize: 12.sp,
                  color: AppColors.color_999999,
                ),
              ),
            ],
          ),
          SizedBox(height: 12.h),
          Container(
            height: 165.h,
            width: double.infinity,
            padding: const EdgeInsets.all(16),
            decoration: const BoxDecoration(
              image: DecorationImage(
                image: AssetImage('assets/images/home_hd/home_hd_meet_bg.png'),
                fit: BoxFit.cover,
              ),
              borderRadius: BorderRadius.all(Radius.circular(8)),
            ),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text('线上采购会议室', style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold, color: Colors.white),),
                Text('Пересекая горы и моря, встречая будущее', style: TextStyle(fontSize: 10, color: Colors.white),),
                const SizedBox(height: 15,),
                Image.asset(controller.liveBtnImg, height: 20,),
              ],
            ),
          ),
        ],
      ),
    );
  }

  /// 构建最新货源
  Widget _buildLatestFreight() {
    return Container(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            margin: const EdgeInsets.only(left: 16),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Text(
                  '最新货源',
                  style: TextStyle(
                    fontSize: 16.sp,
                    fontWeight: FontWeight.w600,
                    color: AppColors.color_333333,
                  ),
                ),
                SizedBox(height: 5.h),

                Container(width: 40, height: 3, decoration: BoxDecoration(color: Colors.blue, borderRadius: BorderRadius.circular(1.5)),),
              ],
            ),
          ),

          SizedBox(height: 12.h),
          ListView.builder(
            padding: EdgeInsets.zero,
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            itemCount: controller.freightList.length,
            itemBuilder: (context, index) {
              final item = controller.freightList[index];
              return _buildFreightItem(item);
            },
          ),
        ],
      ),
    );
  }

  /// 构建货源项目
  Widget _buildFreightItem(Map<String, dynamic> item) {
    return Container(
      margin: EdgeInsets.only(bottom: 12.h),
      padding: EdgeInsets.all(16.w),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12.r),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.1),
            blurRadius: 8,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 头部信息
          Row(
            children: [
              Text(
                '发布时间: ${item['publishTime']}',
                style: TextStyle(
                  fontSize: 11.sp,
                  color: AppColors.color_333333,
                ),
              ),
              const Spacer(),
              Text(
                item['category'],
                style: TextStyle(
                  fontSize: 12.sp,
                  color: AppColors.color_333333,
                ),
              ),
            ],
          ),
          SizedBox(height: 12.h),
          // 路线信息
          Container(
            decoration: BoxDecoration(
              color: Colors.red,
              borderRadius: BorderRadius.circular(12),
              gradient: LinearGradient(
                begin: AlignmentGeometry.topCenter,
                end: AlignmentGeometry.bottomCenter,
                colors: [
                  Color(0xFFEDFAFF),
                  Color(0x20EDFAFF),
                ],
              ),
            ),
            padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 15),

            child: Row(
              children: [
                // 出发地
                Column(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Text(
                      item['fromCity'],
                      style: TextStyle(
                        fontSize: 18.sp,
                        fontWeight: FontWeight.bold,
                        color: AppColors.color_333333,
                      ),
                    ),
                    SizedBox(height: 2.h),
                    Row(
                      children: [
                        Image.asset(
                          'assets/images/ic_中国.png',
                          width: 16.w,
                          height: 12.h,
                        ),
                        SizedBox(width: 4.w),
                        Text(
                          item['fromProvince'],
                          style: TextStyle(
                            fontSize: 12.sp,
                            color: AppColors.color_666666,
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
                // 中间箭头
                Expanded(
                  child: Center(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Text(
                          '途经${item['viaCount']}',
                          style: TextStyle(
                            fontSize: 12.sp,
                            color: AppColors.color_278AFF,
                          ),
                        ),
                        Image.asset('assets/images/home_hd/home_hd_list_arrow.png', width: 50,)
                      ],
                    ),
                  ),
                ),
                // 目的地
                Column(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Text(
                      item['toCity'],
                      style: TextStyle(
                        fontSize: 18.sp,
                        fontWeight: FontWeight.bold,
                        color: AppColors.color_333333,
                      ),
                    ),
                    SizedBox(height: 2.h),
                    Row(
                      children: [
                        Image.asset(
                          'assets/images/ic_俄罗斯.png',
                          width: 16.w,
                          height: 12.h,
                        ),
                        SizedBox(width: 4.w),
                        Text(
                          item['toState'],
                          style: TextStyle(
                            fontSize: 12.sp,
                            color: AppColors.color_666666,
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ],
            ),
          ),
          SizedBox(height: 12.h),
          // 货物信息
          Text(
            item['cargoInfo'],
            style: TextStyle(fontSize: 11.sp, color: AppColors.color_333333),
          ),
          SizedBox(height: 4.h),
          Text(
            item['tracking'],
            style: TextStyle(fontSize: 11.sp, color: AppColors.color_333333),
          ),
          SizedBox(height: 12.h),
          Divider(height: 1, color: AppColors.color_EEEEEE,),
          SizedBox(height: 12.h),
          // 查看详情按钮
          Align(
            alignment: Alignment.centerRight,
            child: GestureDetector(
              onTap: () => controller.onViewDetails(item['id']),
              child: Container(
                padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 6.h),
                decoration: BoxDecoration(
                  border: Border.all(color: AppColors.color_EEEEEE, width: 1),
                  borderRadius: BorderRadius.circular(16.r),
                ),
                child: Text(
                  '查看详情',
                  style: TextStyle(
                    fontSize: 12.sp,
                    color: AppColors.color_666666,
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
